<template>
<div class="app">
  <el-container>

    <el-header>
      <PilotComponent/>
  <el-backtop></el-backtop>
    </el-header>
    <el-main class="main">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-row :gutter="40">

            <el-col :span="4">
              <el-tooltip class="item" effect="dark" content="反馈" placement="top">
                <el-popover
                    placement="bottom"
                    title="反馈"
                    width="200"
                    trigger="manual"
                    v-model="visible"
                    content="联系邮箱:maotao@email.com">
                  <el-button slot="reference" type="primary" icon="el-icon-message" circle @click="visible =! visible"/>

                </el-popover>
              </el-tooltip>

            </el-col>
            <el-col :span="16"><span>{{bookName}}</span></el-col>
            <el-col :span="4">
              <div v-if="userBookshelf[this.bookName]===undefined && bookshelfToggle">
                <el-button @click.stop="joinBookShelf(book)" round icon="el-icon-plus">书架</el-button>
              </div>
              <div v-else>
                <el-button round @click.stop="delBookFromBookshelf(book)"  icon="el-icon-close">书架</el-button>
              </div>
            </el-col>
          </el-row>



        </div>
        <div v-if="content===''">
          <el-skeleton :rows="6" animated />
        </div>
        <div v-else class="content" v-html="content" @keyup.right="current_change(currentPage+1)"/>
      </el-card>

      <el-pagination
          background
          layout="prev, pager, next , jumper"
          :total="total"
          :current-page="currentPage"
          @current-change="current_change"
          :page-size="1"/>

    </el-main>
    <el-footer>
      <FooterComponent/>
    </el-footer>
  </el-container>



</div>
</template>

<script>
import {getChapterTotal, readBook, updateUser} from "@/utils/api";
import PilotComponent from "@/components/pilot/PilotComponent";
import FooterComponent from "@/components/footer/FooterComponent";

export default {
  name: "ChapterPage",
  components: {FooterComponent, PilotComponent},
  props: {

  },
  data() {
    return {
      bookName : String,
      book : Object,
      bookshelfToggle : true,
      content : '',
      currentPage :1,
      visible : false,
      total : 1,
      index : 0
    }
  }, methods: {
    delBookFromBookshelf(item){
      delete this.$store.state.user.bookshelf[item.bookName];
      if(this.getBookshelf[item.bookName]=== undefined){
        this.$notify.success("已移除书架")
        this.$forceUpdate()
        this.updateUser()
      }else{
        this.$notify.error("删除失败")
      }

    },
    //获取总章节
    async getChapterTotal(){
      getChapterTotal({
        bookNumber : this.book.bookNumber
      }).then(res=>{
        if(res.code === 200){
          this.total = res.objects;
        }else{
          console.error(res)
          this.notify(res.message,"异常","error")
        }
      })
    },
    //获取阅读历史起始点
    getBookStartByBookName(bookName){
       // console.log("getBookStartByBookName")
      try {
        const history = this.userHistory[bookName];
        // console.log(history)
        if(history.bookStart!==0 && history.bookStart!==NaN &&history.bookStart!==null){
          return history.bookStart;
        }
      }catch (e) {

        return 1;
      }

    },
    //获取章节
    current_change(newPage){
       // console.log(newPage)
      this.currentPage = newPage
      readBook(
        this.book.bookNumber,
        this.currentPage
      ).then(res=>{
            // console.log(res)
            if(res.code === 200){
              this.content = res.objects;
            }else{
              console.error(res)
              this.notify(res.message,"异常","error")
            }
        })
      javascript:scroll(0,0)
      // console.log(this.book)
      this.book.bookStart = Math.max(this.book.bookStart,this.currentPage)
      if(this.userBookshelf[this.bookName]!==undefined){
        this.userBookshelf=this.book
      }
      this.userHistory = this.book
      this.updateUser()
    },
    //加入书架
    joinBookShelf(item){
      this.getBookshelf = item
      if(this.getBookshelf[item.bookName]){
        this.$notify.success("加入书架成功")
        //强制刷新
        this.$forceUpdate()
        this.updateUser()
      }else{
        this.$notify.error("加入失败")
      }

    },
    //更新用户信息
    async updateUser(){
      var user = this.getUser;
      user.password=''
      // console.log(user)
      updateUser(user).then(res=>{
        // console.log("同步")
        // console.log(res)
      })
    },
    notify(msg,title,type) {
      this.$notify({
        title: title,
        message: msg,
        type: type
      });
    },
    turnPages(amount){
      if( this.content === '')
        return
      const targetPage = this.currentPage + amount
      if(targetPage > this.total)
        return
      if(targetPage <= 0)
        return

      this.current_change(targetPage)

    }

  }, watch: {}, computed: {
    userHistory:{
      get(){
        return this.getUser.history;
      },
      set(value){
        let user=this.getUser;
        user.history[this.bookName]=value
        this.getUser = user;
      }
    },
    userBookshelf:{
      get(){
        return this.getUser.bookshelf;
      },
      set(value){
        let user=this.getUser;
        user.bookshelf[this.bookName]=value
        this.getUser = user;

      }
    },
    getBookshelf:{
      get(){
        return this.$store.getters.getUser.bookshelf;
      },
      set(value){
        let user=this.getUser;
        user.bookshelf[value.bookName]=value
        this.getUser = user;

      }
    },
    getUser:{
      get(){
        return this.$store.getters.getUser;
      },
      set(value){
        return this.$store.commit("setUser",value);
      }
    }
  },created() {
    const _this = this;
    document.onkeydown = function(e) {
      if(e.key === 'ArrowLeft'){
        _this.turnPages(-1)
      }else if(e.key === 'ArrowRight'){
        _this.turnPages(1)
      }
    }

    this.book = this.$route.params.book
    //拦截直接访问
    if(this.book == undefined){
      this.$router.go(-1)
      return;
    }
    if(this.book.bookStart ==null)
      this.book.bookStart =1
    //获取书名
    this.bookName = this.book.bookName;
    //获取起始章节
    this.currentPage = this.getBookStartByBookName(this.bookName);
    //获取总章节
    this.getChapterTotal(this.bookName)
    //获取文章
    this.current_change(this.currentPage);
  }
}
</script>

<style scoped>
.main{
  margin: 0 auto;
}
.box-card{
  width: 850px;

}
.content{
  width: 800px;
  text-wrap: normal;
  text-align: left;
  text-indent: 2em;
  line-height: 2rem;
}
</style>